package com.example.server.service;

import cn.hutool.system.oshi.OshiUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.server.mapper.SysServerMapper;
import com.example.server.po.SysServer;
import com.example.utils.IPUtils;
import com.example.utils.RandomUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author chentao
 * @version 1.0
 * @description: TODO
 * @date 2025/3/22 下午12:26
 */
@Service
public class SysServerServiceImpl extends ServiceImpl<SysServerMapper, SysServer> implements SysServerService, ApplicationContextAware {

    private String host;

    @Value("${server.port}")
    private long port;

    private long serverId = 0;

    private ApplicationContext applicationContext;

    @Override
    public String getHost() {
        if (StringUtils.isEmpty(host)) {
            this.host = IPUtils.getIP();
        }
        return this.host;
    }

    @Override
    public long getPort() {
        return this.port;
    }

    @Override
    public int getProcessId() {
        return OshiUtil.getOs().getProcessId();
    }

    @Override
    public String getOsName() {
        return System.getProperty(OS_NAME);
    }

    @Override
    public String getOsFamily() {
        return OshiUtil.getOs().getFamily().trim();
    }

    @Override
    public String getUserDir() {
        return System.getProperty(USER_DIR);
    }

    @Override
    public String getJavaVersion() {
        return System.getProperty(JAVA_VERSION);
    }

    @Override
    public long getCurrentServerId() {
        if (this.serverId == 0) {
            this.serverId = IPUtils.combineIpAndPort(getHost(), getPort());
        }
        return this.serverId;
    }

    @Override
    public SysServer getCurrentSysServer() {
        return getById(getCurrentServerId());
    }

    @Override
    public List<SysServer> getAllServer() {
        return list();
    }

    @Override
    public List<Long> getAllServerIds() {
        return getBaseMapper().getAllServerIds();
    }

    @Override
    public long getRandomServerKey() {
        List<Long> activeServers = getAllServerIds();
        if (activeServers.isEmpty()) {
            return getCurrentServerId();
        }
        int index = RandomUtils.randomInt(activeServers.size());
        return activeServers.get(index);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
